import Http from './index'

const uploadApi = {
  uploadBase64: 'files/upload/image/base64',
  uploadBase: 'files/upload/file'
}

/**
 * base64上传
 * @param base64 base64 字符串
 * @returns 媒体资源的网络路径
 */
export async function fetchUploadToBase64(base64: string): Promise<string> {
  const upload = await Http.Post(uploadApi.uploadBase64, {
    'base64Str': base64
  })

  if (upload && upload.items) {
    return upload.items.url
  }
  return ''
}

/**
 * base64上传
 * @param base64 base64 字符串
 * @param suffix 文件后缀。mp3、mp4、jpg 等
 * @returns 媒体资源的网络路径
 */
export async function fetchUploadToBlobPath(blobPath: string, suffix: string): Promise<string> {
  const blob = await fetch(blobPath).then(res => res.blob()) // blobPath使用的是当前地址，理论上不存在跨域
  const param = new FormData()
  const name = `${new Date().getTime()}.${suffix}`
  param.append('file', blob, name)
    
  const res = await Http.Post(uploadApi.uploadBase, param, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Call-Source': 'PPT'
    }
  })

  if (res && res.items) {
    return res.items.url
  }

  return ''
}
